<template>
  <div>
    <ZWDrawer ref="zwRef" @submit="save" @close="close" @cancel="cancel">
      <div class="contents">
        <el-form :model="form" label-width="138px">
          <el-form-item label="客户公海" required>
            <el-select v-model="form.cust_seas_id" placeholder="请选择客户公海"
              ><el-option
                v-for="(item, index) in seaids"
                :value="item.id"
                :label="item.name"
                >{{ item.name }}</el-option
              ></el-select
            >
          </el-form-item>
          <el-form-item
            :label="item.attr_name"
            v-for="item in systemAttrList"
            :required="item.is_required == 2"
          >
            <el-input
              v-model="item.current_val"
              v-if="item.attr_type == 'input'"
              :disabled="item.disabled"
              :placeholder="'请输入' + item.attr_name"
            />
            <el-select
              v-model="item.current_val"
              v-if="item.attr_type == 'select'"
              :disabled="item.disabled"
              :placeholder="'请选择' + item.attr_name"
            >
              <el-option
                v-for="items in item.attr_val"
                :value="items.key"
                :label="items.val"
                >{{ items.val }}</el-option
              >
            </el-select>
          </el-form-item>
          <el-form-item
            :label="item.attr_name"
            v-for="item in getData"
            :required="item.is_required == 2"
          >
            <CascaderItem v-if="item.attr_type == 'pca'" :itemValue="item" />
            <el-input
              v-model="item.current_val"
              v-if="['mobile', 'textbox', 'email'].includes(item.attr_type)"
              :placeholder="'请输入' + item.attr_name"
            />
            <!-- <el-input v-model="item.current_val" type="textarea" v-if="item.attr_type == 'textarea'" :placeholder="'请输入' + item.attr_name" /> -->
            <el-checkbox-group
              v-if="item.attr_type == 'muti_select'"
              v-model="item.current_val"
              :placeholder="'请选择' + item.attr_name"
            >
              <el-checkbox v-for="it in item.attr_val" :key="it.key" :label="it.key">{{
                it.val
              }}</el-checkbox>
            </el-checkbox-group>

            <el-select
              v-model="item.current_val"
              v-if="item.attr_type == 'select'"
              :disabled="item.disabled"
              :placeholder="'请选择' + item.attr_name"
            >
              <el-option
                v-for="items in item.attr_val"
                :value="items.key"
                :label="items.val"
                >{{ items.val }}</el-option
              >
            </el-select>
            <el-input
              style="width: 100%"
              v-if="item.attr_type == 'textarea'"
              type="textarea"
              v-model="item.current_val"
              :placeholder="`请输入${item.attr_name}`"
              :rows="5"
            />
            <el-date-picker
              v-if="item.attr_type == 'date'"
              style="width: 100%"
              value-format="YYYY-MM-DD"
              v-model="item.current_val"
              type="date"
              placeholder="请选择日期"
            >
            </el-date-picker>

            <ZWUpload
              :upInfo="fileInfo"
              @submit="getFile"
              v-if="item.attr_type == 'picture'"
            >
            </ZWUpload>
          </el-form-item>
          <el-form-item label="客户阶段" required>
            <el-select v-model="form.cust_stage_id" placeholder="请选择客户阶段"
              ><el-option
                v-for="(item, index) in levelid"
                :value="item.id"
                :label="item.name"
                >{{ item.name }}</el-option
              ></el-select
            > </el-form-item
          ><el-form-item label="客户来源">
            <el-select v-model="form.cust_source_id" placeholder="请选择线索来源"
              ><el-option
                v-for="(item, index) in sourceid"
                :value="item.id"
                :label="item.name"
                >{{ item.name }}</el-option
              ></el-select
            >
          </el-form-item>

          <el-form-item label="所属员工" required>
            <el-tag
              v-for="item in creators"
              :key="item.name"
              class="staffs_item"
              closable
              @close="handleClose(item)"
              :type="item.id"
            >
              {{ item.name }}
            </el-tag>
            <div>
              <el-button @click="openDepart">选择员工</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </ZWDrawer>
    <ZWDepart ref="DepartRef" @submit="getDepart" type="1" />
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, watch } from "vue";
import { ElMessage } from "element-plus";
import ZWDrawer from "@/components/ZWDrawer.vue";
import ZWDepart from "@/components/ZWDepart.vue";
import ZWUpload from "@/components/ZWUpload.vue";
import {
  getCustomerData,
  getClubSource,
  customerStatus,
  customerList,
  getCustomerSave,
} from "@/api/customer/clubManage/commonSea";
import CascaderItem from "@/components/customerCenter/CascaderItem.vue";
import { getSetionId } from "@/utils/utils";
const emit = defineEmits(["close", "submit"]);
const props = defineProps(["open", "seas_id", "rowid", "title"]);
const zwRef = ref(null);
const DepartRef = ref(null);
const creators = ref<any>([]);
let form = reactive({
  cust_seas_id: 0, // 默认选择默认公海
  clue_grade_id: "", //线索等级id
  source_id: "", //线索来源id
  work_user_id: "",
  mobile: "",
});
let file = reactive({ url: "", files: [] });
const fileInfo = reactive({
  type: 1,
  prop: "cover",
  file: file.files,
  limitSize: 2,
  limitNum: 1,
  multiple: false,
  acceptFile: ".jpg,.jpeg,.png,.gif,.bmp,.webp",
});
const systemAttrList = ref([
  {
    attr_name: "姓名",
    attr_type: "input",
    attr_val: [],
    current_val: "",
    code: "NAME",
    key: "name",
    is_required: 0,
    disabled: false,
  },
  {
    attr_name: "手机号",
    attr_type: "input",
    attr_val: [],
    current_val: "",
    code: "MOBILE",
    key: "mobile",
    is_required: 2,
    disabled: false,
  },
  {
    attr_name: "性别",
    attr_type: "select",
    attr_val: [],
    current_val: "",
    code: "SEX",
    key: "sex",
    is_required: 0,
    disabled: false,
  },
  {
    attr_name: "年龄",
    attr_type: "input",
    attr_val: [],
    current_val: "",
    code: "AGE",
    key: "age",
    is_required: 0,
    disabled: false,
  },
  {
    attr_name: "邮箱",
    attr_type: "input",
    attr_val: [],
    current_val: "",
    code: "EMAIL",
    key: "email",
    is_required: 0,
    disabled: false,
  },
  {
    attr_name: "地址",
    attr_type: "input",
    attr_val: [],
    current_val: "",
    code: "ADDRESS",
    key: "address",
    is_required: 0,
    disabled: false,
  },
  {
    attr_name: "公司",
    attr_type: "input",
    attr_val: [],
    current_val: "",
    code: "COMPANY",
    key: "company",
    is_required: 0,
    disabled: false,
  },
  {
    attr_name: "QQ",
    attr_type: "input",
    attr_val: [],
    current_val: "",
    code: "QQ_NUMBER",
    key: "qq_number",
    is_required: 0,
    disabled: false,
  },
  {
    attr_name: "微信号",
    attr_type: "input",
    attr_val: [],
    current_val: "",
    code: "WX_NUMBER",
    key: "wx_number",
    is_required: 0,
    disabled: false,
  },
  {
    attr_name: "备注",
    attr_type: "input",
    attr_val: [],
    current_val: "",
    code: "REMARK",
    key: "remark",
    is_required: 0,
    disabled: false,
  },
]);
const getData = ref([]);
const getDetail = () => {
  getCustomerData({ clue_id: props.rowid }).then((res: any) => {
    creators.value.splice(0, creators.value.length, res.dist_work_user);
    form.work_user_id = res.dist_work_user.id;

    for (const attrItem of res.cust_attr.custom_attr) {
      if (attrItem.attr_type === "muti_select") {
        attrItem.current_val = [];
      }
    }
    getData.value = res.cust_attr.custom_attr;
    let data = res.info.system_attr.attr_val;
    let selectData = res.cust_attr.system_attr.attr_val;
    systemAttrList.value.forEach((item: any) => {
      item.current_val = data[item.code] ? data[item.code] : "";
      item.disabled = data[item.code] ? true : false;
      if (item.attr_type == "select") {
        item.attr_val = selectData[item.code];
      }
    });
  });
};
const seaids = ref([]); //公海列表
const levelid = ref([]); //线索等级列表
const sourceid = ref([]); //线索来源
//获取公海列表
const getSeaList = () => {
  seaids.value = [];
  customerList({ page: 1, page_size: 1000 }).then((res: any) => {
    seaids.value = res;
    const defaultCustomer = res.find((item: any) => item.is_default === 1);
    form.cust_seas_id = defaultCustomer.id;
  });
};
//获取线索等级
const getLevelList = () => {
  levelid.value = [];
  customerStatus({ page: 1, page_size: 1000 }).then((res: any) => {
    res.forEach((item) => {
      // if (item.status == 1) {
      //筛选已开启的线索等级
      levelid.value.push(item);
      // }
    });
  });
};
//获取线索来源
const getSourceList = () => {
  sourceid.value = [];
  getClubSource({ page: 1, page_size: 1000 }).then((res: any) => {
    res.data.forEach((item) => {
      if (item.status == 1) {
        //筛选开始的线索来源
        sourceid.value.push(item);
      }
    });
  });
};
const save = () => {
  if (!systemAttrList.value[1].current_val) {
    ElMessage.warning("请填写手机号");
    return;
  } else {
    let rex = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
    if (!rex.test(systemAttrList.value[1].current_val)) {
      ElMessage.warning("请输入合法的手机号");
      return;
    }
  }

  // if (!form.clue_grade_id) {
  //   ElMessage.warning('请选择线索等级')
  //   return
  // }
  // if (!creators.value.length) {
  //   ElMessage.warning('请选择归属员工')
  //   return
  // }
  const data = getData.value;
  data.forEach((item) => {
    item.attr_val = item.current_val;
    // delete item.current_val
    delete item.is_required;
    delete item.disabled;
    delete item.system_code;
  });
  const param = {
    address: "",
    company: "",
    email: "",
    name: "",
    age: "",
    qq_number: "",
    mobile: "",
    remark: "",
    sex: "",
    wx_number: "",
  };
  systemAttrList.value.forEach((item: any) => {
    if (item.key == "mobile") {
      form.mobile = item.current_val;
      delete param.mobile;
    }
    param[item.key] = item.current_val;
  });
  getCustomerSave({
    ...form,
    custom_attr: data,
    clue_id: props.rowid,
    system_attr: param,
  }).then((res) => {
    ElMessage.success("转化成功");
    emit("submit");
    emit("close");
    zwRef.value.drawer = false;
  });
};
const cancel = () => {
  for (let key in form) {
    if (key != "custom_attr" && key != "seas_id") {
      form[key] = "";
    }
    getData.value.forEach((item) => {
      item.current_val = "";
    });
  }
};
const openDepart = () => {
  // 记录是那个员工弹框
  DepartRef.value.multiple = false;
  DepartRef.value.departVisble = true;
  DepartRef.value.selectedMember = [...creators.value];
};
// 获取部门成员
const getDepart = (res: any) => {
  creators.value = res;
  form.work_user_id = getSetionId("id", creators.value).length
    ? getSetionId("id", creators.value)[0]
    : "";
  DepartRef.value.departVisble = false;
};
// 员工移除
const handleClose = (data: any) => {
  creators.value = [];
  form.work_user_id = "";
  DepartRef.value.removeItem(data);
};
const close = () => {
  emit("close");
};
const getFile = (data: any) => {
  file.url = data.length ? data[0].url : "";
  file.files = data;
  getData.value.forEach((item) => {
    if (item.attr_type == "picture") {
      item.current_val = file.url;
    }
  });
};
watch(
  () => props.open,
  (val) => {
    if (val) {
      // form.seas_id = props.seas_id
      zwRef.value.resetMsg = "重置";
      zwRef.value.drawerMsg = "保存";
      zwRef.value.isResetShow = true;
      zwRef.value.title = props.title;
      getDetail();
      getSourceList();
      getLevelList();
      getSeaList();
      zwRef.value.drawer = true;
      zwRef.value.width = "600px";
    }
  }
);
</script>
<style scoped lang="scss">
.contents {
  padding: 16px 0;
}
.el-select {
  width: 100%;
}
</style>
